<?php
/*
 * 微信
 */
namespace app\home\controller;

use app\common\controller\IndexBase;
use think\facade\Session;
use think\facade\Db;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Raw;
use app\common\model\System;

class Wechat extends IndexBase
{
    protected function initialize()
    {
        parent::initialize();
        $options = System::get_config_by_code('wechat');
        $this->app = Factory::officialAccount($options);;
    }

    public function index()
    {   
        // 校验开发者微信服务器
        // $this->ckServer();exit();
        $this->app->server->push(function ($message) {
            switch ($message['MsgType']) {
                case 'event':
                    $openid = $message['FromUserName']; // 用户的 openid
                    $messageEvent = $message['Event'];
                    if ($messageEvent ==='subscribe') {//关注触发事件
                        $count = Db::table('wechat')->where(['openid'=>$openid])->count();
                        $userInfo = $this->app->user->get($openid);
                        if ($count) {//二次关注
                            $userInfo['update_time'] = time();
                            Db::table('wechat')->where(['openid'=>$openid])->update($userInfo);
                        }else{//首次关注
                            $userInfo['create_time'] = time();
                            Db::table('wechat')->insert($userInfo);
                        }
                    }elseif($messageEvent ==='unsubscribe'){//取消关注触发事件
                        Db::table('wechat')->where(['openid'=>$openid])->update(['subscribe'=>0,'update_time'=>time()]);
                    }
                    $messageKey = (isset($message['EventKey']) && !empty($message['EventKey'])) ? $message['EventKey'] : '';
                    $returnInfo = $this->eventHandler($messageEvent, $messageKey);
                    return $returnInfo;
                    break;
                case 'text':
                    //回复一条文本消息
                    $res = Db::table('goods')->where(['status'=>1])->where(function ($query) use ($message){$query->where('name','LIKE', '%'.trim($message['Content']).'%');})->orderRand()->find();
                    if ($res) {
                        $res['img'] = json_decode($res['img']);
                        $data = [];
                        $data['touser']= $message['FromUserName'] ;
                        $data['msgtype'] = 'link';
                        $data['link']= [
                            'title'=>$res['name'],
                            'description'=>$res['goods_brief'],
                            'url'=>$this->request->domain().'/good/type/'.md6($res['id']).'.html',
                            'thumb_url'=>$res['img'][0]
                        ];
                        $content = new Raw(json_encode($data));
                    }else{
                        $content = '未查询到【'.$message["Content"].'】,换个关键字试试';
                    }

                    $this->app->customer_service->message($content)->to($message['FromUserName'])->send();// 实现人工智能;
                    break;
                case 'image':
                    //回复一张图片消息
                    // $content = new Image($message["MediaId"]);
                    // $this->app->customer_service->message($content)->to($message['FromUserName'])->send();
                    // break;
                    //回复一条链接消息
                    $data = [];
                    $data['touser']= $message['FromUserName'] ;
                    $data['msgtype'] = 'link';
                    $data['link']= [
                        'title'=>'2025春秋季时尚潮长袖上衣气质女神套装秋装新款女装 三件套韩版',
                        'description'=>'2025春秋季时尚潮长袖上衣气质女神套装秋装新款女装 简介',
                        'url'=>$this->request->domain().'/good/type/'.md6(10).'.html',
                        'thumb_url'=>$message["PicUrl"]
                    ];
                    $content = new Raw(json_encode($data));
                    $this->app->customer_service->message($content)->to($message['FromUserName'])->send();
                    break;
                    $image = $message["PicUrl"];
                    return $image.'收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }
        });
        $response = $this->app->server->serve();
        // 将响应输出
        $response->send(); 
    }
    /*
     * 校验开发者服务器
     */
    private function ckServer()
    {
        $response = $this->app->server->serve();
        // 将响应输出
        $response->send();

    }

    /*
     * 菜单栏中type为click的按钮才会发送return的消息回去
     * eventKey是设置菜单时type为click的key值
     */
    private function eventHandler($messageEvent, $eventKey)
    {
        $messageEvent = strtolower($messageEvent);
        switch ($messageEvent) {
            case 'subscribe': // 订阅事件
                return '您好！欢迎关注『千城万店』：www.qcwd.com ☏服务热线：18336308393 欢迎您为我们提供宝贵的建议。';
                break;
            case 'unsubscribe': // 取消订阅事件
                // TODO 可以添加日志等其他逻辑
                return '';
                break;
            case 'click': // 处理菜单点击事件
                return $this->menuClickEventHandler($eventKey);
                break;
            case 'scan': // 处理微信扫描二维码事件
                return $this->scanEventHandler($eventKey);
                break;
            default:
                return "{$messageEvent}, {$eventKey}";
                break;
        }
    }
    
    /*
     * 扫描事件处理程序
     * eventKey是设置菜单时type为click的key值
     */
    private function scanEventHandler($eventKey)
    {
       switch ($eventKey) {
           case 'scan_test': // 场景值ID
               return '使用微信扫描了二维码，扫描事件key值为: ' . $eventKey;
               break;
           default:
               return '使用微信扫描了二维码';
               break;
       }
    }
    /*
     * 菜单栏中type为click的按钮才会发送return的消息回去
     * eventKey是设置菜单时type为click的key值
     */
    private function menuClickEventHandler($eventKey)
    {
        switch ($eventKey) {
            case 'menu_click_test':
                return '点击了一级菜单的 menuClick 按钮';
                break;
            case 'sub_menu_click_test':
                return '点击了二级菜单的 subMenuClick 按钮';
                break;
            default:
                return "嘻嘻";
                break;
        }
    }
    /*
     * 生成二维码
     */
    public function createQrcode()
    {
        $content = $this->request->get('content');
        if (empty($content)) return json(['code' => -1, 'message' => 'content must be set']);
        $expire = $this->request->get('expire', 600);
        $type = $this->request->get('type', 'tmp');
        $createRes = $this->genQrcode($type, $content, $expire);

        return $createRes ? json(['code' => 1, 'message' => '保存成功']) : json(['code' => -1, 'message' => '保存失败']);
    }

    public function genQrcode($type, $content, $expire=600)
    {
        if ($type == 'tmp') {
            $result = $this->app->qrcode->temporary($content, $expire);
        } else {
            $result = $this->app->qrcode->forever($content);
        }
        $url = $this->app->qrcode->url($result['ticket']); // 生成的二维码的图片地址
        $uploadService = new UploadService; // 这里面检查了文件保存目录，这里我保存到了public目录下的upload目录
        $saveFilename = $uploadService->genSaveFilename('genQrcode', 'jpg'); // 生成了一个可用的保存文件名
        $imgContent = file_get_contents($url);
        $saveRes = file_put_contents($saveFilename, $imgContent);
        // TODO 记录保存图片地址
        return $saveRes;
    }

    /*
     * 获取AccessToken
     */
    public function getAccessToken()
    {
        $op = '123';//$this->getOpenId();
        halt($op);
        $accessToken = $this->app->access_token;
        $token = $accessToken->getToken();
        dump($token);

    }

    /**
     * 获取用户列表
     *
     * @return array users
     */
    public function getUserList()
    {
        $userList = $this->app->user->list($nextOpenId = null);
        return json($userList);
    }

    /**
     * 获取单个用户的信息
     *
     * @param string $openId 用户openId
     * @return array
     */
    public function getUserInfo()
    {
        $openId = $this->request->get('openId');
        if (empty($openId)) return json(['code' => -1, 'message' => 'openId must be set']);
        $userInfo = $this->app->user->get($openId);
        return json($userInfo);
    }

    /**
     * 获取多个用户的信息
     *
     * @param array $openIds 用户openId，二维数组
     * @return array
     */
    public function getUsersInfo($openIds = [])
    {
        if (empty($openIds)) return json(['code' => -1, 'message' => 'openIds must be set']);
        $users = $this->app->user->select($openIds);
        return json($users);
    }

    /**
     * 设置备注
     *
     * @param string $openId 用户openId
     * @param string $remark 备注信息
     * @return boolean
     */
    public function setRemark()
    {
        $openId = $this->request->get('openId');
        if (empty($openId)) return json(['code' => -1, 'message' => 'openId must be set']);
        $remark = $this->request->get('remark');
        if (empty($remark)) return json(['code' => -1, 'message' => 'remark must be set']);
        $res = $this->app->user->remark($openId, $remark);
        return json($res);
    }

    /**
     * 获取拉黑用户的列表  默认获取全部
     *
     * @param array $beginOpenid
     * @return array
     */
    public function blackUserList()
    {
        $res = $this->app->user->blacklist();
        return json($res);
    }

    /**
     * 拉黑用户
     *
     * @param string/array $openIds 用户openId，单个是字符串，多格式数组
     * @return
     */
    public function block()
    {
        $openId = $this->request->get('openId');
        if (empty($openId)) return json(['code' => -1, 'message' => 'openId must be set']);
        $res = $this->app->block($openIds);
        return json($res);
    }

    /**
     * 取消拉黑用户
     *
     * @param string/array $openIds 用户openId，单个是字符串，多格式数组
     * @return
     */
    public function unblock()
    {
        $openId = $this->request->get('openId');
        if (empty($openId)) return json(['code' => -1, 'message' => 'openId must be set']);
        $res = $this->app->unblock($openIds);
        return json($res);
    }
    



}
